/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.brucexx.wedding.controller;

import java.io.Serializable;

import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.brucexx.wedding.util.StringHelper;

/**
 * 
 * @author Administrator
 */
public class FileProcessListener implements ProgressListener, Serializable {

	private static final Log logger = LogFactory
			.getLog(FileProcessListener.class);

	/**
	 * 
	 */
	private static final long serialVersionUID = -4526664848302311452L;

	private volatile  long bytesRead = 0;
	private volatile  long lastBytesRead = 0;
	private volatile  long contentLength = 0;
	private volatile  long beginListenerTime = 0;
	private volatile  long lastuploadTime = 0;
	private volatile float curSpeedAmount = 0;
	private volatile String curSpeed;
	private volatile String leftTime;
	private volatile int percent = 0;
	private volatile long totalTimeAmout = 0;
	private volatile String totalTime;
	private volatile String avgSpeed;
	private volatile static int na2sec = 1000 * 1000 * 1000;

	public FileProcessListener() {
		this.beginListenerTime = System.nanoTime();
		this.lastuploadTime = System.nanoTime();
	}

	@Override
	public void update(long l, long l1, int i) {
		if (l == l1) {
			totalTimeAmout = System.nanoTime() - beginListenerTime;
			totalTime = StringHelper
					.getTime(((float) totalTimeAmout / (float) na2sec));
			avgSpeed = StringHelper.getFileSize(l1 * na2sec / totalTimeAmout,
					null) + "/秒";
		}
		this.bytesRead = l;
		if (this.contentLength == 0) {
			contentLength = l1;
		}
		long begin = System.nanoTime();
		long interval = begin - this.lastuploadTime;
		long onceReadBytes = bytesRead - lastBytesRead;
		if (interval != 0) {
			curSpeedAmount = onceReadBytes * na2sec / interval;
			curSpeed = StringHelper.getFileSize(curSpeedAmount, null) + "/秒";
			leftTime = StringHelper
					.getTime(((contentLength - bytesRead) / curSpeedAmount));
		}
		percent = (int) (bytesRead * 100 / contentLength);
		this.lastBytesRead = bytesRead;
		this.lastuploadTime = System.nanoTime();
	}

	/**
	 * @return the bytesRead
	 */
	public long getBytesRead() {
		return bytesRead;
	}

	public double getPercent() {
		return percent;
	}

	/**
	 * @return the contentLength
	 */
	public long getContentLength() {
		return contentLength;
	}

	public String getLeftTime() {
		return this.leftTime;
	}

	public String getCurSpeed() {
		return curSpeed;
	}

	public boolean isCompeleted() {
		return bytesRead == contentLength;
	}

	/**
	 * @return the totalTime
	 */
	public String getTotalTime() {
		return totalTime;
	}

	/**
	 * @return the avgSpeed
	 */
	public String getAvgSpeed() {
		return avgSpeed;
	}

	public String toString() {
		return "uploadSize:[" + bytesRead + "]bytes, totalSize["
				+ contentLength + "]bytes";
	}
}
